<template>
  <div>
    <table border="1">
      <thead>
        <tr v-show="hasTheadGroup">
          <th v-for="(item, index) in headTips" v-show="!item.hide" :key="index">
            <span>{{ item.text }}</span>
          </th>
        </tr>
        <tr>
          <th v-for="(item, index) in cols" :key="index" v-show="!item.hide">
            <span>{{ item.text }}</span>
            <span class="text-muted ml4" v-show="store[item.dataField]?.length">
              {{ store[item.dataField]?.length }}
              <span v-show="item.name == 'creatives'">组</span>
            </span>
            <span v-show="item.hasEmpty && item.dataField && store[item.dataField]?.length" @click="eventEmptySelectItems(item)"
              >清空</span
            >
            <span class="fr cur-p v1-f-success editIcon" @click="eventShowEditPop(item)">{{ item.editTypeText || "编辑" }}</span>
            <slot :name="item.headSlot"></slot>
          </th>
        </tr>
      </thead>
      <tbody style="">
        <tr style="" class="content">
          <td v-for="item in cols" :key="item.name" :data-name="item.name" v-show="!item.hide">
            <div class="cell" :style="{ 'height': (item.height || 350) + 'px', 'overflow-y': 'auto' }">
              <slot :name="item.slot"></slot>
              <component :is="renderMap.get(item.render)?.(item) ?? renderMap.get('default')"></component>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <component :is="modalComponentUri" :key="modalComponentName"></component>
  </div>
</template>

<script setup lang="ts">
import { inject, defineAsyncComponent, ref, shallowRef, h } from "vue";
import { message, Modal } from "ant-design-vue";
import { EXCHANGE } from "@/config/enum";
import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
import { ADX_FILE_NAME_MAP } from "../dto/strategyDto";

import RenderItems from "@/pages/NewBatchCreateAd/components/render/RenderItems.vue";
import RenderField from "@/pages/NewBatchCreateAd/components/render/RenderField.vue";
import RenderTitlePackages from "@/pages/NewBatchCreateAd/components/render/RenderTitlePackages.vue";
import RenderData from "@/pages/NewBatchCreateAd/components/render/RenderData.vue";
import RenderTarget from "@/pages/NewBatchCreateAd/components/render/RenderTarget.vue";
import RenderCreatives from "@/pages/NewBatchCreateAd/components/render/RenderCreatives.vue";

const store = batchCreateAdStore();

const adxId: any = inject("adxId");
const adxSubId: any = inject("adxSubId");

// 清空
const eventEmptySelectItems = (col: any) => {
  Modal.confirm({
    title: "确认",
    content: `确认要清空所有${col.text}吗？`,
    onOk() {
      if (col.dataField) {
        store[col.dataField] = [];
        // 如果是千川全域推广清空账户
        if (col.name === "account" && adxSubId.value === EXCHANGE.QIANCHUAN_QY) {
          store.Plan.select_plans = [];
        }
        // 如果是小米删除转化追踪,转化出价,自定义人群,落地页,监控链接
        if (col.name === "account" && adxId.value === EXCHANGE.XIAOMI) {
          store.Plan.conversionsMap = {};
          store.Plan.converBidMap = {};
          store.Campaign.audienceMap = {};
          store.CreativeConfig.ladingPageMap = {};
          store.Monitor = {};
        }
      }
    },
  });
};

const modalComponentName = ref(); //保存需要加载的的组件名称
const modalComponentUri = shallowRef();

const eventShowEditPop = (col: any) => {
  // 如果是趣头条创意素材
  if (col.name === "creatives" && adxId.value === EXCHANGE.QUTOUTIAO) {
    if (!store.CreativeConfig.type) {
      message.warning("请在创意基本信息中设置创意样式");
      return;
    }
  }

  // 如果是趣头条监控链接
  if (col.name === "monitor" && adxId.value === EXCHANGE.QUTOUTIAO) {
    if (!store.AccountItems.length) {
      message.warning("请先选择账号");
      return;
    }
  }

  // 如果是小米定向包
  if (col.name === "target" && adxId.value === EXCHANGE.XIAOMI) {
    if (store.Campaign?.displayType == 34) {
      message.warning("商店-富媒体版位无需设置定向包");
      return;
    }
  }

  // 异步组件
  modalComponentName.value = col.name;

  let adxFileName: any = adxSubId.value ? ADX_FILE_NAME_MAP[adxSubId.value] : ADX_FILE_NAME_MAP[adxId.value];

  switch (col.name) {
    case "account":
      modalComponentUri.value = defineAsyncComponent({
        loader: () => import("../modal/SelectAccount.vue"),
        delay: 200,
      });
      break;
    default:
      modalComponentUri.value = defineAsyncComponent({
        loader: () => import(`../adx/${adxFileName}/${col.name}/index.vue`),
        delay: 200,
      });
      break;
  }
};

const props = defineProps<{
  hasTheadGroup: boolean;
  headTips: any[];
  cols: any[];
}>();


// 单元格渲染方法
// 渲染账号
const renderAccount = (col: any) => {
  return h(RenderItems, {
    col: col,
    dataField: col.dataField,
    hasExternalId: true,
    hasRule: false,
    hasEdit: false,
  });
};
// 渲染计划、单元基本信息、创意基本信息的表单
const renderForm = (col: any) => {
  return h(RenderData, {
    col: col,
    dataField: col.dataField,
  });
};
// 渲染定向包
const renderTarget = (col: any) => {
  return h(RenderTarget, {
    col: col,
    dataField: col.dataField,
    ruleField: "targets_rule",
  });
};
// 渲染标题包
const renderTitlePackage = (col: any) => {
  return h(RenderTitlePackages, {
    col: col,
    dataField: col.dataField,
    hasExternalId: false,
    hasRule: false,
    hasEdit: true,
    // ruleField: "titles_rule",
  });
};
const renderMultiTitlePackage = (col: any) => {
  if (col.dataFields?.length) {
    const children = col.dataFields
      .map((dataField: any, index: number) => {
        if (store[dataField]?.length) {
          return [
            h("div", col.fieldLabels?.[index]),
            h(RenderTitlePackages, {
              key: `title-package-${dataField}`,
              col: col,
              dataField,
              hasExternalId: false,
              hasRule: false,
              hasEdit: true,
            }),
          ];
        }
        return null;
      })
      .filter(Boolean);
    return h("div", children);
  }
};
// 渲染创意素材
const renderCreatives = (col: any) => {
  return h(RenderCreatives, {
    col: col,
    dataField: col.dataField,
  });
};

const renderField = (col: any) => {
  return h(RenderField, {
    col: col,
    dataField: col.dataField,
  });
};

const renderMap = ref<Map<string, any>>(new Map());
renderMap.value.set("default", h("div", null, "缺少渲染方法！"));
renderMap.value.set("renderAccount", renderAccount);
renderMap.value.set("renderForm", renderForm);
renderMap.value.set("renderTarget", renderTarget);
renderMap.value.set("renderTitlePackage", renderTitlePackage);
renderMap.value.set("renderMultiTitlePackage", renderMultiTitlePackage);
renderMap.value.set("renderCreatives", renderCreatives);
renderMap.value.set("renderField", renderField);

</script>

<style scoped></style>
